package com.byapp.fast.amqp.receiver;

import com.byapp.fast.amqp.enums.AmqpEnum;
import com.byapp.fast.common.enums.ResultEnum;
import com.byapp.fast.common.utils.EnumUtils;
import com.byapp.fast.common.utils.JsonUtils;
import com.byapp.fast.modules.match.dto.MatchMsgEventDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 外部消息接收者
 */
@Component
@Slf4j
public class OuterMatchEventReceiver {

    @Autowired
    private DirectExchange direct;

    @Autowired
    private RabbitTemplate template;

    @RabbitListener(queues = "outerMatchEvent")
    public void receive(Message message) {
        String msg = new String(message.getBody());
        MatchMsgEventDTO matchMsgEventDTO;
        Integer msgType;
        try {
            matchMsgEventDTO = JsonUtils.fromJson(msg, MatchMsgEventDTO.class);
            msgType = Integer.parseInt(matchMsgEventDTO.getMsgType());
        } catch (Exception e) {
            log.error("【外部消息处理】JSON格式化异常，参数：消息体={}", msg);
            return;
        }

        // 根据传入的消息类型找到对应的枚举类
        AmqpEnum.MessageTypeEnum codeEnum = EnumUtils.getByCode(msgType, AmqpEnum.MessageTypeEnum.class);
        if (codeEnum == null) {
            log.error("【外部消息处理】消息类型不存在，参数：消息类型={}，原因={}", msgType, ResultEnum.ILLEGAL_PARAM.getMsg());
            return;
        }
        String key = codeEnum.getQueueName();
        log.info("【{}消息】队列={},消息体={}", codeEnum.getMsg(), codeEnum.getQueueName(), msg);
        // 使用exchange+routingKey的方式发送消息到队列中
        template.convertAndSend(direct.getName(), key, matchMsgEventDTO);
    }

}
